﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Reflection;


public partial class MB_ActionHandler : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString(); ;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        security hdds = new security();
        if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);
        if (!Page.IsPostBack && Request.QueryString["action"] != null)
        {
            string action = Request.QueryString["action"];
            switch (action)
            {
                case "usr_del":
                    displayUserDeletion();
                    break;
            }
        }
    }
    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }

    #region User deletion functions
    private void displayUserDeletion()
    {
        security hds = new security();
        try
        {
            if (Request.QueryString["pgs_id"] != null && Request.QueryString["pgs_id"] == "8c2cb032c3b3516d" && Request.QueryString["DPK"] != null && Request.QueryString["DPK"] != "")
            {
                if (hds.checkRecordAccess(Request.QueryString["DPK"].ToString(), Request.QueryString["pgs_id"].ToString()))
                {
                    Assign_To.Text = new HDDatabase().GetColumnValue("select user_id from sy_usr where af_row_id = '650a333596bbf348';");
                    div_usr_del.Visible = true;
                }
                else
                    lblMessage.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", false);
            }
            else
                lblMessage.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", false);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("MB_ActionHandler: displayUserDeletion : Error : " + ex.Message);
        }
    }

    protected void btnConfirm_Click(object sender, EventArgs e)
    {
        HDDatabase hdd = new HDDatabase();
        Master MA = new Master();
        ScreenReader SR = new ScreenReader();
        SqlCommand sqlCommand = null;
        SqlConnection sqlConn = null;
        
        try
        {
            DataRow dr_usr = hdd.GetTableRow("select * from sy_usr where user_id = '" + Assign_To.Text.Replace("'", "''") + "';");
            if (dr_usr == null)
                lblMessage.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;Target user is invalid.", true);
            else
            {
                string strPagesetRowID = Request.QueryString["pgs_id"].ToString();
                string strDelKey = Request.QueryString["DPK"].ToString();
                Session["DPK"] = strDelKey;

                DataSet dsePageInfo = new DataSet();
                PageInfoLoad PIL = new PageInfoLoad();
                dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowID);

                bool blnStatus = MA.ProcessOperation(dsePageInfo, strDelKey, "DELETE");
                Session["DPK"] = null;

                if (blnStatus)
                {
                    string sAuditLog_Row_id = SR.getHashKey(), SQL = "";
                    SQL = "insert into sy_audit_actions ([log_seq],[object_id],[action_by],[action],[action_result],[log_date],[af_row_id],[created_by],[owner_id],[created_at],[modified_at],[modified_by]) " +
                        "values (1,'" + dsePageInfo.Tables["Page"].Rows[0]["object_id"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','DELETE','1','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + sAuditLog_Row_id + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "');";

                    SQL += "INSERT INTO [sy_audit_log_key]([key_seq],[attrib_id],[key_value],[log_seq],[af_row_id],[created_by],[owner_id],[created_at],[modified_at],[modified_by]) " +
                        "VALUES (1,'af_row_id','" + strDelKey + "','" + sAuditLog_Row_id + "','" + SR.getHashKey() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "');";

                    SQL += "INSERT INTO [sy_audit_log_value]([attrib_seq],[attrib_id],[old_value],[new_value],[log_seq],[af_row_id],[created_by],[owner_id],[created_at],[modified_at],[modified_by])" +
                        "VALUES (1,'User Deletion','" + strDelKey + "','" + dr_usr["af_row_id"].ToString() + "','" + sAuditLog_Row_id + "','" + SR.getHashKey() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "');";

                    string sProcessRowId = "896e4c6b7050de0b"; // Process Row_id for user deletion
                    string sProcessStaRowId = SR.getHashKey();

                    SQL += "INSERT INTO [sy_process_statistics] ([Process_row_id],[initiated_by],[functional_row_id],[af_row_id],[created_by],[created_at],[modified_at],[modified_by],[owner_id])" +
                         " VALUES ('" + sProcessRowId + "','" + Session["user_afrowid"].ToString() + "','" + sAuditLog_Row_id + "','" + sProcessStaRowId +
                         "','" + Session["user_afrowid"].ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + Session["user_afrowid"].ToString() + "', 'e51e0327224a2eb9');";

                    sqlConn = new SqlConnection(HttpContext.Current.Session["dbcon"].ToString());
                    sqlCommand = new SqlCommand(SQL, sqlConn);
                    sqlConn.Open();
                    int Exe = sqlCommand.ExecuteNonQuery();
                    sqlConn.Close();
                    if (Exe > 0)
                    {
                        SQL = "INSERT INTO [sy_processes] ([Process_row_id],[Statistics_row_id],[Company_id],[User_id],[af_row_id],[created_by],[created_at],[modified_at],[modified_by],[owner_id])" +
                             " VALUES ('" + sProcessRowId + "','" + sProcessStaRowId + "','" + Session["company_afrowid"].ToString() + "','" + Session["user_afrowid"].ToString() + "','" + SR.getHashKey() +
                             "','" + Session["user_afrowid"].ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + Session["user_afrowid"].ToString() + "', 'e51e0327224a2eb9');";
                        sqlConn = new SqlConnection(HttpContext.Current.Session["servercon"].ToString());
                        sqlCommand = new SqlCommand(SQL, sqlConn);
                        sqlConn.Open();
                        sqlCommand.ExecuteNonQuery();
                    }
                }
                string sUrlContinue = Request.QueryString["curl"] != null ? HttpUtility.UrlDecode(Request.QueryString["curl"].ToString()) : new Navigator().getUserHomePage();
                Response.Redirect(sUrlContinue, false);
            }
        }
        catch (Exception ex)
        {
            lblMessage.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;" + ex.Message, true);
            LogWriter.WriteLog("MB_ActionHandler: displayUserDeletion : Error : " + ex.Message);
        }
        finally
        {
            if (sqlCommand != null)
                sqlCommand.Dispose();
            if (sqlConn != null)
            {
                if (sqlConn.State.Equals(ConnectionState.Open))
                    sqlConn.Close();
                sqlConn.Dispose();
            }
            SR = null; MA = null; hdd = null;
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        string sUrlContinue = Request.QueryString["curl"] != null ? HttpUtility.UrlDecode(Request.QueryString["curl"].ToString()) : new Navigator().getUserHomePage();
        Response.Redirect(sUrlContinue, false);
    }
    #endregion
}